<?php
/**
 * Created by PhpStorm.
 * User: 六花
 * Date: 2019/5/16
 * Time: 16:17
 */

class Banner_settingApp extends BackendApp{


    var $_banner_mod;
    var $_goods_mod;
    function __construct()
    {
        $this->Banner_settingApp();
    }

    function Banner_settingApp()
    {
        parent::BackendApp();
        $this->_banner_mod =& m('banner_setting');
        $this->_goods_mod =& m('goods');
    }

    function index()
    {
        $banner_model =  & m('banner_setting');
        if($_GET['type_id']){
            $conditions = 'type_id = '.$_GET['id'];
        }else{
            $conditions = '';
        }
        $page = $this->_get_page();
        $res = $this->_banner_mod->find(array(
            'conditions' => $conditions,
            'limit' => $page['limit'],
            'count' => true,
            'order' => "sort_order asc"
        )); //找出所有商城的合作伙伴
        $page['item_count'] = $banner_model->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->assign('order_status_list', array(
            ORDER_PENDING => Lang::get('order_pending'),
            ORDER_SUBMITTED => Lang::get('order_submitted'),
            ORDER_ACCEPTED => Lang::get('order_accepted'),
            ORDER_SHIPPED => Lang::get('order_shipped'),
            ORDER_FINISHED => Lang::get('order_finished'),
            ORDER_CANCELED => Lang::get('order_canceled'),
        ));
        $ads = '';
        $statistics_day_md = &m("statistics_day");
        foreach ($res as $key => &$ad) {
            $ad['banner_url'] && $res[$key]['banner_url'] = WEB_PHOTO_SRC . '/' . $ad['banner_url'];
            $ad['detail_url'] && $res[$key]['detail_url'] = WEB_PHOTO_SRC . '/' . $ad['detail_url'];
            $ads .= ','.$ad['banner_id'];
            $res[$key]['jump_type_value'] = Banner_settingModel::$typeJump[$ad['jump_type']];
//            $res[$key]['count_goods'] = $this->makeSql($ad['banner_id'],$ad['goods_id']);
            $conditions = 'keyword = "view_banner_list_'.$ad['banner_id'].'" AND cond = "browse"';
            $total = $statistics_day_md->getOne("SELECT sum(count) FROM {$statistics_day_md->table} WHERE " . $conditions);
            $ad['amount'] = $total?$total:0;
        }
        $this->assign('banners', $res);
        $this->assign('filtered', $filter? 1 : 0); //是否有查询条件
        $page['item_count'] = $this->_banner_mod->getCount();
        $this->import_resource(array('script' => 'inline_edit.js'));
        $this->_format_page($page);
        $this->assign('ads',substr($ads,1));
        $this->assign('page_info', $page);
        $this->display('banner_setting.index.html');
    }
    //请求商品有效数
    function banner_ids(){
        $banner_ids = $_POST['banner_ids'];
        $banner_model =  & m('banner_setting');
        $sql1 = 'SELECT * FROM ecm_banner_setting where banner_id IN ('.$banner_ids .')';
        $resOld1 = $this->_banner_mod->db->query($sql1);
        while ($chat1 = $this->_goods_mod->db->fetchRow($resOld1)) {
            $c[] = $chat1;
        }
        foreach ($c as $key => $ad) {
            $c[$key]['count_goods'] = $this->makeSql($ad['banner_id'],$ad['goods_id']);
        }
        echo json_encode($c);
        exit();
    }

    function add(){
        if (!IS_POST) {

//            $this->assign('banner_list', $this->get_ad_type_list());
            /* 显示新增表单 */
            $yes_or_no = array(
                1 => Lang::get('yes'),
                0 => Lang::get('no'),
            );
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));
            //调用编辑器资源
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js'));
            $template_name = $this->_get_template_name();
            $style_name = $this->_get_style_name();
            $this->assign('build_editor1', $this->_build_editor(array(
                'name' => 'resign',
                'content_css' => SITE_URL . "/themes/mall/{$template_name}2/styles/{$style_name}2/css/ecmall.css"
            )));

            $this->assign('build_upload1', $this->_build_upload(array('belong' => BELONG_ARTICLE, 'item_id' => 0))); // 构建swfupload上传组件

            $sgrades = array(
                '1' => '首页banner轮播图',
                '2' => '商品列表轮播图',
                '3' => '商品分类轮播图',
                '4' => '个人中心轮播图',
            );
            //
            $this->get_goods();
            //
            $this->assign('jump_type', array(
                'app' => Banner_settingModel::$typeJump['app'],
                'h5' => Banner_settingModel::$typeJump['h5']
            ));
            $this->assign('type', $sgrades);
            $this->assign('yes_or_no', $yes_or_no);
            $this->display('banner_setting.form.html');

        } else {
            $data = array(
                'goods_id' => $_POST['goods_id'],
                'type_id' => $_POST['type_id'],
                'banner_remark' => $_POST['banner_remark'],
                'sort_order' => $_POST['sort_order'],
                'jump_type' => $_POST['jump_type'],
                'banner_description' => $_POST['banner_description']
            );

            if (!$article_id = $this->_banner_mod->add($data)) {  //获取article_id
                $this->show_warning($this->_banner_mod->get_error());
                return;
            } else {
                $this->admin_log("新增banner[" . $_POST['title'] . "]", 1);
            }

            //处理上传的文章LOGO
            $article_logo =  $this->_upload($_FILES,'banner_url');
            $article_logos = $this->_upload($_FILES,'detail_url');
            if ($article_logo === false) {
                return;
            }

            if ($article_logos === false) {
                return;
            }
            //处理商品
            $banner_goods = &m('banner_goods');
            $goods_id = explode(',',$data['goods_id']);
            if(!empty($goods_id) && $data['goods_id']){
                foreach($goods_id as $k=>$v){
                    $newArr['banner_id'] = $article_id;
                    $newArr['goods_id'] = $v;
                    $newArr['sort_order'] = $data['sort_order'][$k];
                    $banner_goods->add($newArr);
                }
            }

            $article_logo  && $article_logos && $this->_banner_mod->edit($article_id, array('banner_url' => $article_logo, 'detail_url' => $article_logos)); //将logo地址记下

            $this->show_message('add_banner_successed', 'back_list', 'index.php?app=banner_setting', 'continue_add', 'index.php?app=banner&amp;act=add'
            );
        }


    }

    function edit(){
        ini_set('display_errors','on');
        error_reporting(E_ALL);
        $ad_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $theme_goods = &m('banner_goods');

        if (!$ad_id)
        {
            $this->show_warning('no_such_banner');
            return;
        }

        if (!IS_POST)
        {
            //调用编辑器资源
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js'));
            $template_name = $this->_get_template_name();
            $style_name = $this->_get_style_name();
            $this->assign('build_editor1', $this->_build_editor(array(
                'name' => 'resign',
                'content_css' => SITE_URL . "/themes/mall/{$template_name}2/styles/{$style_name}2/css/ecmall.css"
            )));

            $this->assign('build_upload1', $this->_build_upload(array('belong' => BELONG_ARTICLE, 'item_id' => 0))); // 构建swfupload上传组件


            $find_data     = $this->_banner_mod->find($ad_id);
            if (empty($find_data))
            {
                $this->show_warning('no_such_banner');

                return;
            }
            $ad    =   current($find_data);
            if ($ad['banner_url'])
            {
                $ad['banner_url']  =   WEB_PHOTO_SRC . "/" . $ad['banner_url'];
                $ad['detail_url']  =   WEB_PHOTO_SRC . "/" . $ad['detail_url'];
            }
//            $this->assign('banner_list', $this->get_ad_type_list());
            /* 显示新增表单 */
            $yes_or_no = array(
                1 => Lang::get('yes'),
                0 => Lang::get('no'),
            );
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));
            $sgrades = array(
                '1' => '首页banner轮播图',
                '2' => '商品列表轮播图',
                '3' => '商品分类轮播图',
                '4' => '个人中心轮播图',
            );

            $sql = "select * from ecm_banner_goods where banner_id = ".$ad_id.' order by sort_order asc';
            $resOld = $theme_goods->db->query($sql);
            while ($chat = $theme_goods->db->fetchRow($resOld)) {
                $goodsInfo[] = $chat;
            }

            if(!empty($goodsInfo)){
                $temp_goods = array();
                $goodsSpec = &m('goodsspec');
                $ids = '';
                $goodsSorts = '';
                foreach ($goodsInfo as $k => $v){
                    if($k == 0){
                        $ids = $v['goods_id'];
                    }else{
                        $ids .= ','.$v['goods_id'];
                    }

                    $in_array = array();
                    $stock_array = array();
                    $temp_goods[$k]['goods_id'] = $v['goods_id'];
                    $c = $this->_goods_mod->get($v['goods_id']);
                    $temp_goods[$k]['goods_name'] = $c['goods_name'];
                    $temp_goods[$k]['times'] = $c['times']?$c['times']:"无";
                    $temp_goods[$k]['default_image'] = WEB_PHOTO_SRC . "/" . $c['default_image'];
                    $temp_goods[$k]['goods_id'] = $v['goods_id'];
                    $temp_goods[$k]['sort_order'] = $v['sort_order'];
                    $retult = $goodsSpec->find(array('conditions'=>"goods_id = ".$v['goods_id']));
                    //声明一个库存数
                    $inventory = 0;
                    foreach ($retult as $key => $vvalue) {
                        $inventory += $vvalue['stock'];
                    }
                    //总库存
                    $temp_goods[$k]['total_inventory'] = $inventory;
                    $res_ss = $goodsSpec->getSpecStockInfo($v['goods_id']);
                    foreach ($res_ss as $key => $value) {
                        $value['international_code'] && !in_array($value['international_code'],$in_array)  ?  $in_array[] = $value['international_code'] : NULL;
                        $value['stock_name'] && !in_array($value['stock_name'],$stock_array) ? $stock_array[] = $value['stock_name'] : NULL;
                    }
                    $in_array ? $temp_goods[$k]['international_code'] = implode('<br>',$in_array) : NULL;
                    $stock_array ? $temp_goods[$k]['stock_name'] = implode('<br>',$stock_array) : NULL;
                }
                $ad['goods'] = $temp_goods;
            }
            //
            $this->get_goods();
//            //排序
//            $this->_bg_mod = & m('banner_goods');
//            $sql = "SELECT IFNULL(MIN(ecm_banner_goods.sort_order),9999) as sort_order FROM ecm_banner_goods";
//            $sort_order = $this->_bg_mod->getAll($sql);
//            $this->assign('sort_order',$sort_order['sort_order']);
            $this->assign('jump_type', array(
                'app' => Banner_settingModel::$typeJump['app'],
                'h5' => Banner_settingModel::$typeJump['h5']
            ));
            $this->assign('type', $sgrades);
            $this->assign('ids', $ids);
            $this->assign('yes_or_no', $yes_or_no);
            $this->assign('banner', $ad);
            $this->display('banner_setting.form.html');
        }
        else
        {
            $find_data     = $this->_banner_mod->find($ad_id);
            if (empty($find_data))
            {
                $this->show_warning('no_such_banner');
                return;
            }

            //删除原图片
            if($_FILES['banner_url'] && $find_data['banner_url'] && $find_data['banner_url'] != $_FILES['banner_url']){
                if(file_exists(WEB_PHOTO_SRC . '/' . $find_data['banner_url'])){
                    unlink(WEB_PHOTO_SRC . '/' . $find_data['banner_url']);
                }
            }
            if($_FILES['detail_url'] && $find_data['detail_url'] && $find_data['detail_url'] != $_FILES['detail_url']){
                if(file_exists(WEB_PHOTO_SRC . '/' . $find_data['detail_url'])){
                    unlink(WEB_PHOTO_SRC . '/' . $find_data['detail_url']);
                }
            }
            $data = array(
                'type_id' => $_POST['type_id'],
                'banner_remark' => $_POST['banner_remark'],
                'sort_order' => $_POST['sort_order'],
                'goods_id'=>$_POST['goods_id'],
                'jump_type' => $_POST['jump_type'],
                'banner_description' => $_POST['banner_description']
            );
            $logo =   $this->_upload($_FILES,'banner_url');
            $logos = $this->_upload($_FILES,'detail_url');

            $logo && $data['banner_url'] = $logo;
            $logos && $data['detail_url'] = $logos;
            if ($logo === false)
            {
                return;
            }
            if ($logos === false)
            {
                return;
            }
            //去重
            $sql = 'Delete from ecm_banner_goods where banner_id = '.$ad_id;
            $theme_goods->db->query($sql);

            $goodsArr = explode(',',$_POST['goods_id']);
            if(!empty($goodsArr) && $_POST['goods_id']){
                foreach($goodsArr as $k=>$v){
                    $newArr['banner_id'] = $ad_id;
                    $newArr['goods_id'] = $v;
                    $newArr['sort_order'] = $_POST['goodsSorts'][$k];
                    $theme_goods->add($newArr);
                }
            }

            $rows=$this->_banner_mod->edit($ad_id, $data);
            if ($this->_banner_mod->has_error())
            {
                $this->show_warning($this->_banner_mod->get_error());
                return;
            }else{
                $this->admin_log("修改手机广告[".$_POST['ad_name']."]",1);
            }

            $this->show_message('edit_banner_successed',
                'back_list',        'index.php?app=banner_setting',
                'edit_again',    'index.php?app=banner_setting&amp;act=edit&amp;id=' . $ad_id);
        }


    }

    function drop(){
        $article_ids = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$article_ids) {
            $this->show_warning('no_such_banner');

            return;
        }
        $article_ids = explode(',', $article_ids);
        $message = 'drop_ok';
        foreach ($article_ids as $key => $article_id) {
            $article = $this->_banner_mod->find(intval($article_id));
            //删除原图片
            if($article['banner_url']){
                if(file_exists(WEB_PHOTO_SRC . '/' . $article['banner_url'])){
                    unlink(WEB_PHOTO_SRC . '/' . $article['banner_url']);
                }
            }
        }
        if (!$this->_banner_mod->drop($article_ids)) {    //删除
            $this->show_warning($this->_banner_mod->get_error());
            return;
        }else{
            $theme_goods = &m('banner_goods');
            $sql = 'Delete from ecm_banner_goods where banner_id = '.$_GET['id'];
            $theme_goods->db->query($sql);
            $this->admin_log(Lang::get('del_banner'), 1);
        }

        $this->show_message('删除成功');

    }

    function get_goods(){
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'goods_name',
                'equal' => 'like',
            ),
            array(
                'field' => 'store_name',
                'equal' => 'like',
            ),
            array(
                'field' => 'brand',
                'equal' => 'like',
            ),
            array(
                'field' => 'closed',
                'type'  => 'int',
            ),
        ));

        // 分类
        $cate_id = empty($_GET['cate_id']) ? 0 : intval($_GET['cate_id']);
        if ($cate_id > 0)
        {
            $cate_mod =& bm('gcategory');
            $cate_ids = $cate_mod->get_descendant_ids($cate_id);
            $conditions .= " AND cate_id" . db_create_in($cate_ids);
        }

        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
                $sort  = 'goods_id';
                $order = 'desc';
            }
        }
        else
        {
            $sort  = 'goods_id';
            $order = 'desc';
        }

        $page = $this->_get_page();
        $goods_list = $this->_goods_mod->get_list(array(
            'conditions' => "1 = 1" . $conditions,
            'count' => true,
            'order' => "$sort $order",
            'limit' => $page['limit'],
        ));
        foreach ($goods_list as $key => $goods)
        {
            $goods_list[$key]['cate_name'] = $this->_goods_mod->format_cate_name($goods['cate_name']);
        }
        $this->assign('goods_list', $goods_list);

        $page['item_count'] = $this->_goods_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

        // 第一级分类
        $cate_mod =& bm('gcategory', array('_store_id' => 0));
        $this->assign('gcategories', $cate_mod->get_options(0, true));
        $this->import_resource(array('script' => 'mlselection.js,inline_edit.js'));
    }

    function _upload($file,$str){
        require_once '../includes/aliyunOss/samples/Common.php';
        $image = $file[$str];
        $imageName = date("YmdHis", time()) . rand(1000,10000);
        $path = 'data/files/mall/banner_setting/'.$str;

        if ($image['error'] == UPLOAD_ERR_NO_FILE) { // 没有文件被上传
            return '';
        }
        import('uploader.lib');             //导入上传类
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
        $uploader->addFile($_FILES[$str]); //上传logo
        if (!$uploader->file_info()) {
            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=banner_setting&amp;act=index');
            return false;
        }
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        if (!$file_path = $uploader->save($path,$imageName)) {   //保存到指定目录，并以指定文件名$ad_id存储
            $this->show_message('上传文件失败！');
            return false;
        }
        $ossClient = new \common;
        $r = $ossClient->putObjectFile('../'.$file_path,$file_path);
        if(!$r['info'] || $r['info']['http_code'] != 200){
            $this->show_message('上传oss失败！');
            return false;
        }
        unlink('../'.$file_path);
        return $file_path;
    }

    public function ajaxPost(){
        $data = $_POST;
        $dataArr = array(
            'goods_id'=>$data['goods_id'],
            'type_id' => $data['type_id'],
            'banner_remark' => $data['banner_remark'],
            'sort_order' => $data['sort_order'],
            'preview' => 2,
            'banner_description' => $_POST['banner_description']
        );
        $banner_goods = &m('banner_goods');

        if($data['banner_id']){
            $find_data     = $this->_banner_mod->find($data['banner_id']);
            if (empty($find_data))
            {
                $this->show_warning('no_such_theme');

                return;
            }
            if($_FILES){
                //删除原图片
                if($_FILES['banner_url'] && $find_data['banner_url'] && $find_data['banner_url'] != $_FILES['banner_url']){
                    if(file_exists(WEB_PHOTO_SRC . '/' . $find_data['theme_url'])){
                        unlink(WEB_PHOTO_SRC . '/' . $find_data['theme_url']);
                    }
                }
                if($_FILES['detail_url'] && $find_data['detail_url'] && $find_data['detail_url'] != $_FILES['detail_url']){
                    if(file_exists(WEB_PHOTO_SRC . '/' . $find_data['detail_url'])){
                        unlink(WEB_PHOTO_SRC . '/' . $find_data['detail_url']);
                    }
                }
            }
            $this->_banner_mod->edit($data['banner_id'],$dataArr);
            if ($this->_banner_mod->has_error()) {  //获取article_id
                $this->show_warning('修改失败');
                return;
            } else {
                $this->admin_log("新增banner[" . $_POST['banner_remark'] . "]", 1);
            }
            $article_id = $data['banner_id'];
            $sql = 'Delete from ecm_banner_goods where banner_id = '.$article_id;
            $banner_goods->db->query($sql);

        }else{
            if (!$article_id = $this->_banner_mod->add($dataArr)) {  //获取article_id
                $this->show_warning($this->_banner_mod->get_error());
                return;
            } else {
                $this->admin_log("新增banner[" . $_POST['banner_remark'] . "]", 1);
            }
        }

        if($_FILES){
            //处理上传的文章LOGO
            $article_logo = $this->_upload($_FILES,'banner_url');
            if ($article_logo === false) {
                return;
            }

            $article_logos = $this->_upload($_FILES,'detail_url');
            if ($article_logos === false) {
                return;
            }
            $article_logos && $dataNew['banner_url'] = $article_logos;
            $article_logo && $dataNew['detail_url'] = $article_logo;
            if ($article_logo === false)
            {
                return;
            }
            if ($article_logos === false)
            {
                return;
            }
            $article_logo  && $article_logos && $this->_banner_mod->edit($article_id, array('banner_url' => $article_logo, 'detail_url' => $article_logos)); //将logo地址记下

        }
        //处理商品
        $goods_id = explode(',',$data['goods_id']);
        if(!empty($goods_id) && $data['goods_id']){
            foreach($goods_id as $k=>$v){
                $newArr['banner_id'] = $article_id;
                $newArr['goods_id'] = $v;
                $newArr['sort_order'] = $data['goodsSorts'][$k];
                $banner_goods->add($newArr);
            }
        }
        $this->show_message('保存成功', 'back_list', 'index.php?app=banner_setting', 'edit_again', 'index.php?app=banner_setting&amp;act=edit&amp;id=' . $article_id
        );

    }

    public function cancelPreview(){
        $data = $_GET;
        if(!$data['id'] || !$data['preview']){
            $this->show_warning('参数错误');
            return;
        }
        $saveData['preview'] = $data['preview'];
        if(!$save = $this->_banner_mod->edit($data['id'],$saveData)){
            $this->show_warning($this->_banner_mod->get_error());
            return;
        } else {
            $this->admin_log("xiugaibanner[" . $_POST['title'] . "]", 1);
        }
        $this->show_message('保存成功', 'back_list', 'index.php?app=banner_setting');
    }

    public function previewJson(){
        $page = $_POST['page'] * 10;
        $ad_id = isset($_POST['banner_id']) ? intval($_POST['banner_id']) : 0;
        $ad = $this->_banner_mod->get($ad_id);
        $banner_goods = &m('banner_goods');
        $sql = "select * from ecm_banner_goods where banner_id = ".$ad_id.' order by sort_order asc';
        $resOld = $banner_goods->db->query($sql);
        while ($chat = $banner_goods->db->fetchRow($resOld)) {
            $goodsInfo[] = $chat;
        }
        $sql1 = "SELECT cc.store_id as sto_id,ifnull(cc.ico,'') as ico,gl.* FROM ecm_discount d right join ( SELECT
g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock)
as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or
gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when
locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then 0 else
1 end)) > 0 then true else false end as is_exist,MAX(case when gsp.stock=0 or gsp.price=0.00 or
gsp.discount_price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.discount_price end) as
end_discount_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3 and
gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or
gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case
when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.price end) as
first_cost_price,ifnull(g.label,'') as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3
and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as
discount,bg.sort_order,ifnull(SUBSTRING(g.times,1,2 ),'') as ftimes,ifnull(SUBSTRING(g.times,3 ),'') as ltimes FROM
ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_banner_goods bg WHERE (
g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id =
g.goods_id and g.goods_id = bg.goods_id AND g.if_show=1 AND g.closed=0 AND s.state=1 AND bg.banner_id = ".$ad_id." AND g.goods_id in (".$ad['goods_id'].")) GROUP BY g.goods_id HAVING
is_exist = true ORDER BY bg.sort_order ASC,ifnull(SUBSTRING(g.times,3),'') DESC,ifnull(SUBSTRING(g.times,1,2 ),'') ASC  LIMIT ".$page.",10) gl on d.goods_id = gl.goods_id left join
ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1 GROUP BY gl.goods_id ORDER BY gl.sort_order
ASC,ifnull(SUBSTRING(gl.times,3 ),'') DESC,ifnull(SUBSTRING(gl.times,1,2 ),'') ASC" ;

        $c = array();
        $resOld1 = $this->_goods_mod->db->query($sql1);
        while ($chat1 = $this->_goods_mod->db->fetchRow($resOld1)) {
            $c['lists'][] = $chat1;
        }
        echo json_encode($c);
        exit();
    }

    function preview(){
        $ad_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$ad_id)
        {
            $this->show_warning('no_such_theme');
            return;
        }

        if (!IS_POST) {
            $ad = $this->_banner_mod->get($ad_id);
            if (empty($ad)) {
                $this->show_warning('no_such_theme');

                return;
            }
//            $ad = current($find_data);
            if ($ad['banner_url']) {
                $ad['banner_url'] = WEB_PHOTO_SRC . "/" . $ad['banner_url'];
                $ad['detail_url'] = WEB_PHOTO_SRC . "/" . $ad['detail_url'];
            }
//            $this->assign('theme_list', $this->get_ad_type_list());
            /* 显示新增表单 */
            $yes_or_no = array(
                1 => Lang::get('yes'),
                0 => Lang::get('no'),
            );
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));
            $sgrades = array(
                '1' => '首页theme轮播图',
                '2' => '商品列表轮播图',
                '3' => '商品分类轮播图',
                '4' => '个人中心轮播图',
            );
            $goods_spec = &m('goodsspec');
            $banner_goods = &m('banner_goods');
            $sql = "select * from ecm_banner_goods where banner_id = ".$ad_id.' order by sort_order asc';
            $resOld = $banner_goods->db->query($sql);
            while ($chat = $banner_goods->db->fetchRow($resOld)) {
                $goodsInfo[] = $chat;
            }

            if (!empty($goodsInfo)) {
                $temp_goods = array();
//                foreach ($goodsInfo as $k => $v) {
//                    $temp_goods[$k]['goods_id'] = $v['goods_id'];
                    $sql1 = "SELECT cc.store_id as sto_id,ifnull(cc.ico,'') as ico,gl.* FROM ecm_discount d right join ( SELECT
g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock)
as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or
gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when
locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then 0 else
1 end)) > 0 then true else false end as is_exist,MAX(case when gsp.stock=0 or gsp.price=0.00 or
gsp.discount_price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.discount_price end) as
end_discount_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3 and
gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or
gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case
when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.price end) as
first_cost_price,ifnull(g.label,'') as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3
and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as
discount,bg.sort_order,ifnull(SUBSTRING(g.times,1,2 ),'') as ftimes,ifnull(SUBSTRING(g.times,3 ),'') as ltimes FROM
ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_banner_goods bg WHERE (
g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id =
g.goods_id and g.goods_id = bg.goods_id AND g.if_show=1 AND g.closed=0 AND s.state=1 AND bg.banner_id = ".$ad_id." AND g.goods_id in (".$ad['goods_id'].")) GROUP BY g.goods_id HAVING
is_exist = true ORDER BY bg.sort_order ASC,ifnull(SUBSTRING(g.times,3),'') DESC,ifnull(SUBSTRING(g.times,1,2 ),'') ASC  LIMIT 0,10) gl on d.goods_id = gl.goods_id left join
ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1 GROUP BY gl.goods_id ORDER BY gl.sort_order
ASC,ifnull(SUBSTRING(gl.times,3 ),'') DESC,ifnull(SUBSTRING(gl.times,1,2 ),'') ASC" ;

                    $resOld1 = $this->_goods_mod->db->query($sql1);
                    while ($chat1 = $this->_goods_mod->db->fetchRow($resOld1)) {
                        $c[] = $chat1;
                    }
                    foreach($c as $cKey=>$cValue){
                        $c[$cKey]['default_image'] = WEB_PHOTO_SRC . "/" . $cValue['default_image'];
                    }
                }
                $ad['goods'] = $c;
            $this->get_goods();
            $this->assign('type', $sgrades);
            $this->assign('yes_or_no', $yes_or_no);
            $this->assign('theme', $ad);
            $this->display('banner_setting.preview.html');
        }
    }

    //更改原来数据结构
    public function goods_item(){
        $id = $_GET['id'];
        $info = $this->_banner_mod->find(array("conditions"=>'banner_id ='.$id));
        $info = array_values($info);
        $theme_goods = &m('banner_goods');
        $sql = "select * from ecm_banner_goods where banner_id = ".$id.' order by sort_order asc';
        $resOld = $theme_goods->db->query($sql);
        while ($chat = $theme_goods->db->fetchRow($resOld)) {
            $goodsInfo[] = $chat;
        }
        $goods_id = array_values($goodsInfo);

        $ids = '';
        foreach($goods_id as $k=>$v){
            if($k == 0){
                $ids = $v['goods_id'];
            }else{
                $ids .= ','.$v['goods_id'];
            }
        }
        $arr = array('goods_id'=>$ids);

        $this->_banner_mod->edit($id,$arr);
    }

    //跟APP统一的查询方式
    function makeSql($ad_id,$goods_id){
        $sql1 = "SELECT cc.store_id as sto_id,ifnull(cc.ico,'') as ico,gl.* FROM ecm_discount d right join ( SELECT
g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock)
as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or
gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when
locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then 0 else
1 end)) > 0 then true else false end as is_exist,MAX(case when gsp.stock=0 or gsp.price=0.00 or
gsp.discount_price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.discount_price end) as
end_discount_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3 and
gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or
gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case
when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3 and gsp.price >4582.00) then null else gsp.price end) as
first_cost_price,ifnull(g.label,'') as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3
and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as
discount,bg.sort_order,ifnull(SUBSTRING(g.times,1,2 ),'') as ftimes,ifnull(SUBSTRING(g.times,3 ),'') as ltimes FROM
ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_banner_goods bg WHERE (
g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id =
g.goods_id and g.goods_id = bg.goods_id AND g.if_show=1 AND g.closed=0 AND s.state=1 AND bg.banner_id = ".$ad_id." AND g.goods_id in (".$goods_id.")) GROUP BY g.goods_id HAVING
is_exist = true ORDER BY bg.sort_order ASC,ifnull(SUBSTRING(g.times,3),'') DESC,ifnull(SUBSTRING(g.times,1,2 ),'') ASC) gl on d.goods_id = gl.goods_id left join
ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1 GROUP BY gl.goods_id ORDER BY gl.sort_order
ASC,ifnull(SUBSTRING(gl.times,3 ),'') DESC,ifnull(SUBSTRING(gl.times,1,2 ),'') ASC" ;

        $c = array();
        $resOld1 = $this->_goods_mod->db->query($sql1);
        while ($chat1 = $this->_goods_mod->db->fetchRow($resOld1)) {
            $c[] = $chat1;
        }
        return count($c);
    }

}